package com.rx.core.bean;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;

import java.util.concurrent.Callable;

@Slf4j
public class CaffeineCache implements Cache {

    private String name;
    private com.github.benmanes.caffeine.cache.Cache
            <java.lang.Object,
                    java.lang.Object> cache;

    CaffeineCache(String name, com.github.benmanes.caffeine.cache.Cache
            <java.lang.Object,
                    java.lang.Object> cache){
      this.name = name;
      this.cache = cache;
    }
    @Override
    public String getName() {
        return name;
    }

    @Override
    public Object getNativeCache() {
        return cache;
    }

    @Override
    public ValueWrapper get(Object key) {
        //log.info("token:"+key);
        Object value = cache.get(key,(k)->{return null;});
        return new SimpleValueWrapper(value);
    }

    @Override
    public <T> T get(Object key, Class<T> type) {

        return (T)cache.get(key,(k)->{
            return null;
        });
    }

    @Override
    public <T> T get(Object key, Callable<T> valueLoader) {

        return (T)cache.get(key,(k)->{
            try {
                return valueLoader.call();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        });
    }

    @Override
    public void put(Object key, Object value) {
        cache.put(key,value);
    }

    @Override
    public void evict(Object key) {
       cache.invalidate(key);
    }

    @Override
    public void clear() {
        cache.cleanUp();
    }
}
